package com.taotao.listener;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import org.apache.camel.component.file.strategy.FileChangedExclusiveReadLockStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import com.taotao.item.pojo.Item;
import com.taotao.pojo.TbItem;
import com.taotao.pojo.TbItemDesc;
import com.taotao.service.ItemService;

import freemarker.core.ParseException;
import freemarker.template.Configuration;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.Template;
import freemarker.template.TemplateNotFoundException;

/**
 * 监听器
 * 获取消息
 * 执行生成静态页面
 * @title ItemChangeGenHtmlMessageListener
 * <p>description</p>
 * <p>company: www.itheima.com</p>
 * @author 天火
 * @version 1.0
 */
public class ItemChangeGenHtmlMessageListener implements MessageListener{

	@Autowired
	private ItemService itemService;
	
	@Autowired
	private FreeMarkerConfigurer config;
	
	@Override
	public void onMessage(Message message) {
		// 1.获取数据的消息 拿到商品id
		if(message instanceof TextMessage) {
			TextMessage message2 = (TextMessage) message;
			try {
				Long itemId = Long.parseLong(message2.getText());
				
				//2.从数据库中拿到数据集，调用manager中的方法，拿到数据集
					//引入服务
					//注入服务
					//调用
				TbItem tbItem = itemService.getItemById(itemId);
				Item item = new Item(tbItem);
				TbItemDesc tbItemDesc = itemService.geTbItemDescByItemId(itemId);
				
				//3.生成静态页面，准备好模板
				
				genHtmlFreemarker(item,tbItemDesc);
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
		}
		
		
		
	}

	/**
	 * 生成静态页面
	 * @param item
	 * @param tbItemDesc 
	 */
	private void genHtmlFreemarker(Item item, TbItemDesc tbItemDesc) throws Exception {
		//获取configuration对象，
		Configuration configuration = config.getConfiguration();
		//创建模板，获取文件模板对象
		Template template = configuration.getTemplate("item.ftl");
		//要数据集
		Map model = new HashMap<>();
		model.put("item", item);
		model.put("itemDesc", tbItemDesc);
		
		//输出
		Writer writer = new FileWriter(new File("F:\\freemarker\\item" + "\\" + item.getId() + ".html"));
		template.process(model, writer);
		writer.close();
	}

}
